package com.listeningframework.boot.autoconfigure.webmvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 
 * Spring Context Utils
 *  
 * @author lixining
 * @version $Id: SpringContextUtils.java, v 0.1 2015年4月15日 下午4:41:57 lixining Exp $
 */
@Component
public class SpringContextUtils implements ApplicationContextAware, InitializingBean {
    /**
     * 日志
     */
    private static final Logger       logger = LoggerFactory.getLogger(SpringContextUtils.class);
    /**
     * applicationContext
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * get Bean Instance By Class Type
     *
     * @param clz Bean类型Class
     * @param <T> Bean类型泛型
     * @return T
     */
    public static <T> T getBean(Class<T> clz) {
        Assert.notNull(applicationContext, "applicationContext can not be null");
        return applicationContext.getBean(clz);
    }

    /**
     * Get Bean Instance By Bean Name
     * 
     * @param name bean名称
     * @return Object
     */
    public static Object getBean(String name) {
        Assert.notNull(applicationContext, "applicationContext can not be null");
        return applicationContext.getBean(name);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("===> finish the application context inject");
    }
}
